package com.nfit.shopadmin.service.impl;

import com.nfit.shopadmin.mapper.*;
import com.nfit.shopadmin.service.OrderService;
import com.nfit.shopadmin.utils.RedisIdWorker;
import com.nfit.shopcommon.utils.ThreadLocalUtil;
import com.nfit.shopmodel.dto.order.OrderDto;
import com.nfit.shopmodel.entity.address.Address;
import com.nfit.shopmodel.entity.cart.CartItem;
import com.nfit.shopmodel.entity.order.OrderInfo;
import com.nfit.shopmodel.entity.order.OrderItem;
import com.nfit.shopmodel.entity.product.ProductSku;
import com.nfit.shopmodel.vo.order.GoodsItemOrder;
import com.nfit.shopmodel.vo.order.OrderItemVo;
import com.nfit.shopmodel.vo.order.Summary;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.nfit.shopmodel.vo.common.AuthConst.THREADLOCAL_ADMIN_USER;

/**
 * ClassName:OrderServiceImpl
 * Package:com.nfit.shopadmin.service.impl
 * Description
 *
 * @Author L
 * @Create 2025/1/6 0:10
 */
@Slf4j
@Schema(description = "订单业务")
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Resource
    private RedisIdWorker redisIdWorker; //生成唯一订单id

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private ProductSkuMapper productSkuMapper;

    /**
     * 查询订单项
     */
    @Override
    public OrderItemVo getOrderItem() {
        //返回最终数据
        OrderItemVo orderItemVo = new OrderItemVo();
        //从线程工具类中获取userId
        String userId = ThreadLocalUtil.get(THREADLOCAL_ADMIN_USER);
        //查询选中的商品信息
        List<CartItem> cartItemList = cartMapper.getSelectedCart(userId);
//        log.info("查询选中的商品信息:",cartItemList);
        if (cartItemList.isEmpty()){
            throw new RuntimeException("未查询到选中的商品信息!");
        }
        //封装商品信息数据
        List<GoodsItemOrder> goodsItemOrders = this.encapsulationGoodsItem(cartItemList);
        // 封装结算信息
        Summary summary = this.calculateSummary(goodsItemOrders);
        //封装地址列表
        List<Address> addressList = addressMapper.findByUserId(Long.valueOf(userId));

        //封装最终返回的数据
        orderItemVo.setGoodsItemOrderList(goodsItemOrders); //商品信息
        orderItemVo.setSummary(summary); //结算信息
        orderItemVo.setAddressVoList(addressList);
        return orderItemVo;
    }

    /**
     * 查询立即购买订单项
     */
    @Override
    public OrderItemVo getOrderItemNow(Long skuId,Integer count) {
        //返回最终数据
        OrderItemVo orderItemVo = new OrderItemVo();

        //定义list集合
        List<GoodsItemOrder> list = new ArrayList<>();
        //从线程工具类中获取userId
        String userId = ThreadLocalUtil.get(THREADLOCAL_ADMIN_USER);
        //查询商品sku信息
        ProductSku productSku = productSkuMapper.getProductSkuInfo(skuId);
        if (productSku == null){
            throw new RuntimeException("未查询到选中的商品信息!");
        }
        //封装信息
        GoodsItemOrder goodsItemOrder = new GoodsItemOrder();
        goodsItemOrder.setSkuId(productSku.getId());
        goodsItemOrder.setSkuSpec(productSku.getSkuSpec());
        goodsItemOrder.setCount(count);
        goodsItemOrder.setProductId(productSku.getProductId());
        goodsItemOrder.setProductName(productSku.getSkuName());
        goodsItemOrder.setPicture(productSku.getThumbImg());

        BigDecimal payPrice = productSku.getSalePrice().multiply(new BigDecimal("0.9")); // 默认等于原价
        goodsItemOrder.setPayPrice(payPrice); //实付金额

        goodsItemOrder.setPrice(productSku.getSalePrice()); //原始价格

        // 实付价格小计 = 实付单价 * 购买数量
        BigDecimal totalPayPrice = payPrice.multiply(new BigDecimal(String.valueOf(count)));
        goodsItemOrder.setTotalPayPrice(totalPayPrice); //实付价格小计

        // 原总价 = 原单价 * 购买数量
        BigDecimal totalPrice = productSku.getSalePrice().multiply(new BigDecimal(String.valueOf(count)));
        goodsItemOrder.setTotalPrice(totalPrice);

        //封装商品信息数据
        list.add(goodsItemOrder);
        // 封装结算信息
        Summary summary = this.calculateSummary(list);
        //封装地址列表
        List<Address> addressList = addressMapper.findByUserId(Long.valueOf(userId));

        //封装最终返回的数据
        orderItemVo.setGoodsItemOrderList(list); //商品信息
        orderItemVo.setSummary(summary); //结算信息
        orderItemVo.setAddressVoList(addressList);
        return orderItemVo;
    }

    /**
     * 创建订单
     * @param orderDto 接收前端参数
     * @return 订单id
     */
    @Transactional
    @Override
    public String saveOrderInfo(OrderDto orderDto) {

        //判断参数是否符合
        if (orderDto == null){
            throw new RuntimeException("OrderDto参数不符合!");
        }
        //从线程工具类中获取userId
        String userId = ThreadLocalUtil.get(THREADLOCAL_ADMIN_USER);
        //查询地址
        Address address = addressMapper.findById(orderDto.getAddressId());
        //生成唯一订单id
        Long orderId =  redisIdWorker.nextId("order");
        //封装订单详情主要信息
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setReceiverProvince(address.getFullAddress().split(" ")[0]); //省
        orderInfo.setReceiverCity(address.getFullAddress().split(" ")[1]); //市
        orderInfo.setReceiverDistrict(address.getFullAddress().split(" ")[2]); //区
        orderInfo.setReceiverAddress(address.getAddress()); //详情地址
        orderInfo.setUserId(Long.valueOf(userId)); //userId
        orderInfo.setOrderNo(String.valueOf(orderId)); //订单号
        orderInfo.setTotalPrice(orderDto.getSummary().getTotalPrice()); //商品总额
        orderInfo.setTotalPayPrice(orderDto.getSummary().getTotalPayPrice());//应付金额
        orderInfo.setFeightFee(orderDto.getSummary().getPostFee()); //邮费
        orderInfo.setPayType(orderDto.getPayChannel()); //支付方式
        orderInfo.setOrderStatus(0); //订单状态
        orderInfo.setReceiverName(address.getName()); //收件人name
        orderInfo.setReceiverPhone(address.getPhone()); //收件人手机号
        orderInfo.setBuyerMessage(orderDto.getBuyerMessage()); //备注
        //添加订单详情
        orderInfoMapper.saveOrderInfo(orderInfo);

        //获取skuId,查询sku信息
        List<OrderItem> orderItemList = orderDto.getGoods().stream().map(sku -> {
            ProductSku productSkuInfo = productSkuMapper.getProductSkuInfo(sku.getSkuId());
            if (productSkuInfo == null){
                throw new RuntimeException("未查询到数据!skuId值："+sku.getSkuId());
            }
            //封装数据
            OrderItem orderItem = new OrderItem();
            //生成订单id
            orderItem.setOrderId(orderId); //子订单id,要和订单详情保持一致
            orderItem.setSkuId(sku.getSkuId()); //商品skuId
            orderItem.setSkuName(productSkuInfo.getSkuName()); //skuName
            orderItem.setThumbImg(productSkuInfo.getThumbImg()); //图片
            orderItem.setSkuPrice(productSkuInfo.getSalePrice()); //价格
            orderItem.setSkuNum(sku.getCount()); //购买数量
            orderItem.setPostFee(orderDto.getSummary().getPostFee()); // 邮费（总邮费分摊可按需调整）
            orderItem.setTotalPrice(orderDto.getSummary().getTotalPrice()); // 商品总价
            orderItem.setTotalPayPrice(orderDto.getSummary().getTotalPayPrice()); // 应付总价
            orderItem.setPayChannel(orderDto.getPayChannel());     // 支付方式
            orderItem.setBuyerMessage(orderDto.getBuyerMessage()); // 备注
            return orderItem;
        }).collect(Collectors.toList());
        //log.info("订单项集合：{}",orderItemList);
        orderItemMapper.saveOrderItem(orderItemList);

        //返回订单id
        return String.valueOf(orderId);
    }

    /**
     * 计算结算信息
     * @param goodsItemOrders 商品订单信息
     * @return 结算信息
     */
    private Summary calculateSummary(List<GoodsItemOrder> goodsItemOrders) {
        // 创建 Summary 对象
        Summary summary = new Summary();

        // 商品总价 = 所有商品的原总价相加
        BigDecimal totalPrice = goodsItemOrders.stream()
                .map(GoodsItemOrder::getTotalPrice)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        // 应付金额 = 所有商品的实付价格总和
        BigDecimal totalPayPrice = goodsItemOrders.stream()
                .map(GoodsItemOrder::getTotalPayPrice)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        // 设置邮费
        BigDecimal postFee = new BigDecimal("6");

        // 计算总应付金额 = 实付金额总和 + 邮费
        totalPayPrice = totalPayPrice.add(postFee);

        // 封装数据
        summary.setTotalPrice(totalPrice);       // 商品总价
        summary.setPostFee(postFee);             // 邮费
        summary.setTotalPayPrice(totalPayPrice); // 应付金额

        return summary;
    }

    /**
     * 封装订单商品信息
     * @param cartItemList 选中的购物车集合
     * @return 封装订单商品信息
     */
    private List<GoodsItemOrder> encapsulationGoodsItem(List<CartItem> cartItemList){
        List<GoodsItemOrder> goodsItemOrders = cartItemList.stream().map(cart -> {
            GoodsItemOrder goodsItemOrder = new GoodsItemOrder();
            goodsItemOrder.setSkuSpec(cart.getSpecValue());
            goodsItemOrder.setCount(cart.getSkuCount());
            goodsItemOrder.setProductId(cart.getProductId());
            goodsItemOrder.setProductName(cart.getSkuName());
            // **价格计算逻辑**
            // 实付单价（假设没有优惠则等于原单价，如果有优惠可以在这里加入计算逻辑）
            //定死打九折
            BigDecimal payPrice = cart.getSkuPrice().multiply(new BigDecimal("0.9")); // 默认等于原价
            goodsItemOrder.setPayPrice(payPrice); //实付单价

            goodsItemOrder.setPicture(cart.getThumbImg()); //sku图片
            goodsItemOrder.setPrice(cart.getSkuPrice()); //原始价格
            goodsItemOrder.setSkuId(cart.getSkuId()); //skuId

            // 实付价格小计 = 实付单价 * 购买数量
            BigDecimal totalPayPrice = payPrice.multiply(new BigDecimal(cart.getSkuCount()));
            goodsItemOrder.setTotalPayPrice(totalPayPrice);

            // 原总价 = 原单价 * 购买数量
            BigDecimal totalPrice = cart.getSkuPrice().multiply(new BigDecimal(cart.getSkuCount()));
            goodsItemOrder.setTotalPrice(totalPrice);

            return goodsItemOrder;
        }).collect(Collectors.toList());
        return goodsItemOrders;
    }
}
